/**
 * weapp-js v2.2.3(2022-4-26)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2022 Motigo, Inc.
 * 
 */
import Callback from './utils/callback.js';
import Mox from './index';
import Util from './utils/util';

class File extends Callback {
    constructor() {
        super();
    }
    // 保存图片到相册
    saveImage(opts) {
        this._authSetting()
            .then(() => {
                this._save(opts.filePath)
                    .then(res => {
                        this.success(opts, res);
                    })
                    .catch(err => {
                        this.fail(opts, err);
                    });
            })
            .catch(err => {
                this.fail(opts, err);
            });
    }
    // 生成海报图片
    moImg(opts = {}) {
        if (!opts.data) {
            opts.data = {};
        }
        if (!opts.templateId) {
            this.fail(opts, {
                msg: 'templateId不能为空'
            });
            return;
        }
        wx.request({
            url: 'https://api.scf.moapp.net.cn/release/moimg',
            method: 'POST',
            data: {
                template_id: opts.templateId || '',
                ...opts.data
            },
            success: res => {
                const data = res.data;
                if (data.code === 'SUCCESS') {
                    this.success(opts, data.data);
                } else {
                    this.fail(opts, {
                        msg: data.msg
                    });
                }
            },
            fail: err => {
                this.fail(opts, {
                    msg: err
                });
            }
        });
    }
    // 选择图片
    chooseImg(opts) {
        opts.upload = Util.isUndefined(opts.upload) ? true : opts.upload; // 默认上传图片
        if (!(typeof opts.count === 'number')) {
            this.fail(opts, {
                msg: '请输入正确的count值'
            });
            return false;
        }
        if (opts.count > 9 || opts.count < 1) {
            this.fail(opts, {
                msg: '图片数量最低为1,最大为9'
            });
            return false;
        }
        this._setChooseImgParameter(opts).then(tempFilePaths => {
            console.log('tempFilePaths');
            console.log(tempFilePaths);
            if (opts.upload) {
                Promise.all(
                    tempFilePaths.map(filePath => {
                        return this._upload({
                            filePath: filePath,
                            syncVerify: opts.syncVerify || 0
                        });
                    })
                )
                    .then(urls => {
                        this.success(opts, urls);
                    })
                    .catch(err => {
                        this.fail(opts, err);
                    });
            } else {
                this.success(opts, tempFilePaths);
            }
        });
    }
    // 暴露给外部使用的上传函数
    upload(opts) {
        if (opts.filePath instanceof Array) {
            // 需要上传多张图片
            Promise.all(
                opts.filePath.map(path => {
                    return this._upload({
                        filePath: path,
                        syncVerify: opts.syncVerify || 0
                    });
                })
            )
                .then(urls => {
                    this.success(opts, urls);
                })
                .catch(err => {
                    this.fail(opts, err);
                });
        } else if (typeof opts.filePath === 'string') {
            this._upload({
                filePath: opts.filePath,
                syncVerify: opts.syncVerify || 0
            })
                .then(url => {
                    this.success(opts, url);
                })
                .catch(err => {
                    this.fail(opts, {
                        msg: '请传入正确的filePath值，string或array'
                    });
                });
        } else {
            this.fail(opts);
        }
    }
    // 内部使用的上传函数
    _upload(opts = {}) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: `https://api.scf.moapp.net.cn/release/upload_cos?sync_verify=${
                    opts.syncVerify ? 1 : 0
                }`,
                filePath: opts.filePath,
                name: opts.name || 'file',
                formData: {
                    path: `weapp/${Mox.appid}`
                },
                success: res => {
                    console.log(res);
                    if (res.code === 504) {
                        resolve();
                        // this.fail(opts, {
                        //     msg: '请求超时',
                        // });
                        // return;
                    }
                    const pkg = JSON.parse(res.data);
                    console.log(pkg);
                    if (pkg.code == 0 || pkg.code === 'SUCCESS') {
                        resolve(pkg.data.url);
                        // this.success(opts, pkg.data.url);
                    } else {
                        reject(pkg.msg);
                        // this.fail(opts, pkg.msg);
                    }
                },
                fail: err => {
                    reject(err);
                }
            });
        });
    }

    _setChooseImgParameter(opts) {
        let defaultConfig = {
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera']
        };
        return new Promise((resolve, reject) => {
            wx.chooseImage({
                count: opts.count || defaultConfig.count,
                sizeType: opts.sizeType || defaultConfig.sizeType,
                sourceType: opts.sourceType || defaultConfig.sourceType,
                success: result => {
                    resolve(result.tempFilePaths);
                },
                fail: err => {
                    if (error.errMsg !== 'chooseImage:fail cancel') {
                        this.fail(opts, {
                            msg: err
                        });
                    }
                },
                complete: () => {}
            });
        });
    }

    _sortImgArray(imgArray) {
        return imgArray.sort((a, b) => a.order - b.order);
    }

    _authSetting() {
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success: res => {
                    console.log(res);
                    // 已经授权
                    if (res.authSetting['scope.writePhotosAlbum']) {
                        resolve();
                    } else {
                        // 没有授权 先发起授权
                        wx.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success: () => {
                                // 同意授权
                                resolve();
                            },
                            fail: () => {
                                // 不同意授权
                                wx.hideLoading();
                                wx.showModal({
                                    title: '温馨提示',
                                    content: '您没有授权保存图片，无法保存',
                                    confirmText: '去授权',
                                    success: res => {
                                        if (res.confirm) {
                                            wx.openSetting({
                                                success: () => {
                                                    // 重新尝试保存图片
                                                    resolve();
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        });
    }

    _save(image) {
        console.log('save');
        console.log(image);
        return new Promise((resolve, reject) => {
            console.log('123');
            wx.getImageInfo({
                src: image,
                success: imageInfo => {
                    console.log(imageInfo);
                    wx.downloadFile({
                        url: image,
                        success: res => {
                            wx.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: res => {
                                    resolve(res);
                                },
                                fail: err => {
                                    reject(err);
                                }
                            });
                        },
                        fail: err => {
                            reject(err);
                        }
                    });
                },
                fail: err => {
                    console.log(err);
                    reject(err);
                },
                complete: res => {
                    console.log('complete');
                }
            });
        });
    }
}

export default new File();
